package com.android.delivery.activity.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import com.android.delivery.R
import com.android.delivery.activity.OrderSettleActivity
import com.android.delivery.activity.wangdian.RiderManagementActivity
import com.android.delivery.adapter.LanJianAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.BaseListFragmet
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.dialog.NavigationDialog
import com.android.delivery.dialog.PayMethodDialog
import com.android.delivery.entity.Addr
import com.android.delivery.entity.Logistics
import com.android.delivery.entity.PayWxInfo
import com.android.delivery.entity.even.RefreshConfirmLanj
import com.android.delivery.entity.even.WxPayEvent
import com.android.delivery.entity.request.OrderReq
import com.android.delivery.util.ToastUtils
import com.android.delivery.util.pay.WXPayCommon
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.interfaces.OnConfirmListener
import com.lzy.okgo.model.Response
import com.tencent.mm.opensdk.modelbase.BaseResp
import kotlinx.android.synthetic.main.include_refresh_layout.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 揽件中心-待揽件列表
 */
class LanJianListFragment : BaseListFragmet<Logistics>() {

    val TRANSFER_REQUESTCODE = 1;
    var mClickPos = -1;

    private val jieDanAdapter: LanJianAdapter by lazy {
        LanJianAdapter()
    }

    companion object {
        fun newInstance(type: Int): LanJianListFragment {
            val fragment = LanJianListFragment()
            val bundle = Bundle()
            bundle.putInt(Constants.TYPE, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    private var type: Int = 0

    override fun bindRecyclerView(recLv: RecyclerView?) {
        type = arguments!!.getInt(Constants.TYPE)

        recLv!!.adapter = jieDanAdapter
        jieDanAdapter.setOnItemClickListener(object : LanJianAdapter.OnItemClickListener {
            override fun onConfirmOrder(logistics: Logistics, position: Int) {
                ApiService.pick(this, logistics.logisticsNo!!, object : DialogCallback<LzyResponse<Any>>() {
                    override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                        jieDanAdapter.data.removeAt(position)
                        jieDanAdapter.notifyItemRemoved(position)
                        EventBus.getDefault().post(RefreshConfirmLanj())
                    }
                })
            }

            override fun onCancelOrder(logistics: Logistics, position: Int) {
                XPopup.Builder(activity) //                         .dismissOnTouchOutside(false)
                        .asConfirm("", "是否确认取消？",
                                "取消", "确定",
                                OnConfirmListener {
                                    ApiService.order_cancel(this, logistics.logisticsNo!!, object : DialogCallback<LzyResponse<Any>>() {
                                        override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                                            jieDanAdapter.data.removeAt(position)
                                            jieDanAdapter.notifyItemRemoved(position)
                                        }
                                    })
                                }, null, false)
                        .show()
            }

            override fun onModifyOrder(logistics: Logistics) {
                OrderSettleActivity.self(activity, logistics.type, logistics.getLogictReq())
            }

            override fun onTranferOrder(logistics: Logistics, position: Int) {
                mClickPos = position
                val intent = Intent(activity, RiderManagementActivity::class.java)
                intent.putExtra(Constants.TYPE, RiderManagementActivity.TYPE_TRANSFER)
                intent.putExtra(Constants.ORDER_ID, logistics.logisticsNo)
                startActivityForResult(intent, TRANSFER_REQUESTCODE)
            }

            override fun onPay(logistics: Logistics, position: Int) {
                mClickPos = position;
                val payMethodDialog = PayMethodDialog.newInstance(logistics?.logisticsNo)
                payMethodDialog.setOnGuardDialogListener(object : PayMethodDialog.OnPayMethodDialogListener {

                    override fun onBalancePay(orderNo: String) {
                        balancePay(orderNo, position)
                    }

                    override fun selectPic() {

                    }

                    override fun onWxPay(orderNo: String) {
                        wxPay(orderNo)
                    }

                })
                payMethodDialog.show(childFragmentManager)
            }

            override fun onNavigation(sendAddr: Addr) {
                val navigationDialog = NavigationDialog.newInstance(sendAddr);
                navigationDialog.show(childFragmentManager)
            }

        })
    }

    private fun balancePay(orderNo: String, position: Int) {
        ApiService.orderPayBalance(this, orderNo, object : DialogCallback<LzyResponse<Any>>() {
            override fun onSuccess(response: Response<LzyResponse<Any>>?) {
                ToastUtils.showShort(activity, "支付成功")
                if (mClickPos != -1) {
                    jieDanAdapter.getItem(position)?.paid = true
                    jieDanAdapter.notifyItemChanged(position)
                    mClickPos = -1
                }
            }
        })
    }

    private fun wxPay(orderNo: String) {
        ApiService.orderPayWx(this, orderNo, object : DialogCallback<LzyResponse<PayWxInfo>>() {
            override fun onSuccess(response: Response<LzyResponse<PayWxInfo>>?) {
                val payWxInfo = response!!.body().data
                if (WXPayCommon.getInstance(activity).isWeixinAvilible()) {
                    WXPayCommon.getInstance(activity).sendPayReq(payWxInfo)
                } else {
                    ToastUtils.showShort(activity, getString(R.string.wx_chat_install))
                }
            }
        })
    }

    override fun loadData(page: Int, pageCount: Int) {
        ApiService.pick(this, page, type, object : DialogCallback<LzyResponse<Logistics>>() {
            override fun onSuccess(response: Response<LzyResponse<Logistics>>?) {
                onGetDataSuc(response!!.body().data.records)
            }
        })
    }

    override fun getData(): MutableList<Logistics> {
        return jieDanAdapter.data
    }

    override fun bindData(isRefresh: Boolean, list: MutableList<Logistics>?) {
        if (isRefresh) {
            jieDanAdapter.setNewData(list)
        } else {
            jieDanAdapter.addData(list!!)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: OrderReq) {
        onRefresh(refreshLayout)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: WxPayEvent) {
        if (item.payCode == BaseResp.ErrCode.ERR_OK) {
            ToastUtils.showShort(activity, "支付成功")
            if (mClickPos != -1) {
                jieDanAdapter.getItem(mClickPos)?.paid = true
                jieDanAdapter.notifyItemChanged(mClickPos)
                mClickPos = -1
            }
        } else if (item.payCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
            ToastUtils.showShort(activity, "支付取消")
        } else {
            ToastUtils.showShort(activity, "支付失败")
        }
    }

    override fun isBindEventBus(): Boolean {
        return true
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == TRANSFER_REQUESTCODE) {
            if (resultCode == Activity.RESULT_OK) {
                if (mClickPos != -1) {
                    jieDanAdapter.data.removeAt(mClickPos)
                    jieDanAdapter.notifyItemRemoved(mClickPos)
                }
            }
            mClickPos = -1;
        }
    }
}